package com.sunyuechao.vhr.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sunyuechao.vhr.framework.entity.Hr;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;

/**
 * Created by SunYuechao on 2024/1/30 上午10:17
 * 支持json格式传参
 */
public class JsonFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        if ( !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String contentType = request.getContentType();
        if(!(contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)||contentType.equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE))){
            return super.attemptAuthentication(request, response);
        }else {
            try {
                Hr hr = new ObjectMapper().readValue(request.getInputStream(), Hr.class);
                String username = hr.getUsername();
                username = (username != null) ? username.trim() : "";
                String password = hr.getPassword();
                password = (password != null) ? password : "";
                UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,
                        password);
                // Allow subclasses to set the "details" property
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }
}
